/**
 * Copyright 2009 Emory University
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated  * documentation files (the 
 * "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so, subject to
 * the following conditions: The above copyright notice and this permission
 * notice shall be included in all copies or substantial portions of the
 * Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
 * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
package com.markgrand.structuredSql;

/**
 * Model a qualified table name.
 *
 * @param database
 *      The name of the database that contains the table or null.
 * @param schema
 *      The name of the schema that contains the table or null. 
 * @param table
 *      The unqualified name of the table identified by this object. 
 * @author Mark Grand
 */
class TableName protected (val database:Option[String], 
                           val schema:Option[String],
                           val table:String) extends SQLAppender with SQLIdentifier {
  if (table == null) {
      throw new NullPointerException("Table name may not be null.")
  }

  /**
   * Append an SQL syntax compliant representation of this column identifier
   * to the given StringBuilder object.
   */
  def append(builder: StringBuilder) {
    if (database.isDefined) {
      appendIdentifier(database.get, builder)
      builder.append('.')
    }
    if (schema.isDefined) {
      appendIdentifier(schema.get, builder)
      builder.append('.')
    }
    appendIdentifier(table, builder)
    }
}

object TableName {
  /**
   * Create an unqualified table name.
   * 
   * @param table
   *    The name of the table.
   */
  def apply(table:String) = new TableName(None, None, table)
  
  /**
   * Create a table name qualified with a schema name.
   */
  def apply(schema:String, table:String) = new TableName(None, Some(schema), table)
  
  /**
   * Create a table name qualified with a database and schema name.
   */
  def apply(database:String, schema:String, table:String) = new TableName(Some(database), Some(schema), table)
  
  /**
   * Create a table name that may be qualified with a database and schema name.
   */
  def apply(database:Option[String], schema:Option[String], table:String) = new TableName(database, schema, table)
}
